Specification (PEP 544)
Terminology
We propose to use the term protocols for types supporting structural subtyping.
「構造的サブタイピングをサポートする型についてprotocolという用語を使う」
iterator protocolなどコミュニティで受け入れられているため
we propose to just add a qualifier such as protocol classes when referring to the static type concept.
explicit vs implicit
If a class includes a protocol in its MRO, the class is called an explicit subclass of the protocol.
「クラスがMROにプロトコルを含むとき、そのクラスはプロトコルの明白な部分型と呼ばれる」
(subclassとsubtypeは同じ意味っぽい)
If a class is a structural subtype of a protocol, it is said to implement the protocol and to be compatible with a protocol.
「クラスがプロトコルの構造的部分型であるならば、プロトコルを実装している、かつ、プロトコルと互換であると言われる」
If a class is compatible with a protocol but the protocol is not included in the MRO, the class is an implicit subtype of the protocol.
「クラスがプロトコル互換だが、そのプロトコルがMROに含まれていないならば、そのクラスはプロトコルの暗黙な部分型と呼ばれる」
The attributes (variables and methods) of a protocol that are mandatory for other class in order to be considered a structural subtype are called protocol members.
protocol members
Defining a protocol
例SupportsClose
typing.Protocolを継承したクラス
Protocol members
All methods defined in the protocol class body are protocol members, both normal and decorated with @abstractmethod.
「プロトコルクラスの本体に定義されたメソッドは全てプロトコルのメンバー」
「普通のメソッドも@abstractmethodでデコレートされたメソッドも両方とも(プロトコルのメンバー)」
プロトコルのメソッドをabc.abstractmethodでデコレートできる!
Static methods, class methods, and properties are equally allowed in protocols.
a protocol variable
クラス変数のような書き方をする(name: str)
Explicitly declaring implementation
To explicitly declare that a certain class implements a given protocol, it can be used as a regular base class.
「あるクラスが所与のプロトコルを実装することを明白に宣言するため、プロトコルは通常のベースクラスとして使われうる」
explicitな使い方
So while it’s possible to subclass a protocol explicitly, it’s not necessary to do so for the sake of type-checking.
「明白にプロトコルをサブクラスにすることはできるが、型チェックのためにそうする必要はない」
The default implementations cannot be used if the subtype relationship is implicit and only via structural subtyping – the semantics of inheritance is not changed.
「部分型関係が暗黙で構造的部分型を通してのみならば、(プロトコルの)デフォルトの実装は使えない」
implicitな使い方=プロトコルは継承しない
例のImplicitColorがcomplex_methodを実装していることに表れている
「継承の意味論は変わらない」
例:プロトコルPColor
PColorを継承したNiceColor
継承はせずにメソッド定義をしたImplicitColor
Note that there is little difference between explicit and implicit subtypes, the main benefit of explicit subclassing is to get some protocol methods “for free”.
「explicitなサブクラス化の主な恩恵は、プロトコルのメソッドを"ただで"得られること」
In addition, type checkers can statically verify that the class actually implements the protocol correctly:
「付け加えると、型チェッカはクラスがプロトコルを実際に正しく実装しているか静的に検証する」